﻿//创建时间: 2010-11-19
//创建作者: 李 城
//功能说明: cms系统 缓存操作类
//最后修改: 2011-1-24 
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Caching;
using System.Web;
using System.Collections;
using System.Text.RegularExpressions;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
using Yorkg.CMS.Plugin;
using Yorkg.Base;

namespace Yorkg.CMS.Cache
{
    /// <summary>
    /// 缓存操作类
    /// </summary>
    public class CacheManage_lock //: Yorkg.CMS.Plugin.ICache
    {
        public CacheManager m_CacheBase = CacheFactory.GetCacheManager();
        const   double m_DurationSecond = 60 * 1;
        private static object lockBaseSaveHelper = new object();
        private static object lockHelperCacheKeys = new object();
        public int mintMaxCacheNum = 500;
        
        #region 单个缓存管理
        /// <summary>
        /// 增加一个缓存对象
        /// </summary>
        /// <param name="strKey">主键</param>
        /// <param name="valueObj">cache值</param>
        /// <param name="duration">以秒为单位</param>
        /// <returns></returns>
        public bool Save(string strKey, object objValue, double durationSecond)
        {
            if (Yorkg.Base.Common.TypeHelper.IsEmpty(strKey) || objValue == null )
                return false;
            FlushCacheKeys();
            lock (lockBaseSaveHelper)
            {
                if (durationSecond <= 0)
                    m_CacheBase.Add(strKey, //key
                                    objValue, //value
                                    Microsoft.Practices.EnterpriseLibrary.Caching.CacheItemPriority.Normal,
                                    null,
                                    new AbsoluteTime(TimeSpan.FromSeconds(m_DurationSecond)));
                else
                    m_CacheBase.Add(strKey, //key
                                    objValue, //value
                                    Microsoft.Practices.EnterpriseLibrary.Caching.CacheItemPriority.Normal,
                                    null,
                                    new AbsoluteTime(TimeSpan.FromSeconds(durationSecond)));
                AddKey(strKey);
            }
            return true;
        }
        /// <summary>
        /// 删除一个缓存对象
        /// </summary>
        /// <param name="strKey">主键</param>
        /// <returns></returns>
        public void Remove(string strKey)
        {
            lock (lockBaseSaveHelper)
            {
                if (m_CacheBase.Contains(strKey))
                {
                    m_CacheBase.Remove(strKey);
                    FlushCacheKeys();
                }
            }
        }
        /// <summary>
        /// 清除所有缓存对象 
        /// </summary>
        public void Clear()
        {
            lock (lockBaseSaveHelper)
            {
                if (m_CacheBase.Count > 0)
                    m_CacheBase.Flush();
            }
        }
        /// <summary>
        /// 读取缓存对象
        /// </summary>
        /// <param name="strKey">主键</param>
        /// <returns></returns>
        public object Read(string strKey)
        {
            try
            {
                return m_CacheBase.GetData(strKey);
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 判断缓存对象是否存在
        /// </summary>
        /// <param name="strKey">主键</param>
        /// <returns></returns>
        public bool IsExist(string strKey)
        {
            return (m_CacheBase != null) && m_CacheBase.Contains(strKey) && (m_CacheBase.GetData(strKey) != null);
        }
        #endregion
        
        #region CacheKey的管理

        /// <summary>
        /// 获取所有的CacheKey
        /// </summary>
        /// <returns></returns>
        private string GetAllChaceKeys()
        {
            if (IsExist(CacheKeys.mAllCacheKeys))
            {
                lock (lockHelperCacheKeys)
                {
                    if (IsExist(CacheKeys.mAllCacheKeys))
                    {
                        return m_CacheBase.GetData(CacheKeys.mAllCacheKeys).ToString();
                    }
                }
            }
            return "#";
        }
        /// <summary>
        /// 获取所有的缓存KEY
        /// </summary>
        /// <returns></returns>
        public string GetAllKeys()
        {
            return GetAllChaceKeys();
        }
        /// <summary>
        /// 添加Key
        /// </summary>
        /// <param name="strKey"></param>
        public void AddKey(string strKey)
        {
            if (IsExist(strKey))
            {
                string strAllKeys = GetAllChaceKeys();
                lock (lockHelperCacheKeys)
                {
                    if (IsExist(strKey) && strAllKeys.Contains("#" + strKey + "#") == false)
                    {
                        strAllKeys += strKey + "#";
                        m_CacheBase.Add(CacheKeys.mAllCacheKeys, strAllKeys);
                    }
                }
            }
        }
        /// <summary>
        /// 根据设置的正则表达式清除缓存对象
        /// </summary>
        /// <param name="pattern">正则表达式</param>
        public void RemoveByRegexp(string pattern)
        {
            if (pattern != "" && m_CacheBase.Contains(CacheKeys.mAllCacheKeys))
            {
                foreach (string strTemp in m_CacheBase.GetData(CacheKeys.mAllCacheKeys).ToString().Split('#'))
                {
                    if (Yorkg.Base.Common.TypeHelper.IsEmpty(strTemp) || Regex.IsMatch(strTemp, pattern) == false)
                        continue;
                    else
                    {
                        Remove(strTemp);
                    }
                }
                FlushCacheKeys();
            }
        }
        /// <summary>
        /// 刷新CacheKeys 刷新Cache
        /// </summary>
        private void FlushCacheKeys()
        {
            if (m_CacheBase.Contains(CacheKeys.mAllCacheKeys))
            {
                lock (lockHelperCacheKeys)
                {
                    if (m_CacheBase.Contains(CacheKeys.mAllCacheKeys) && Yorkg.Base.Common.TypeHelper.IsEmpty(CacheKeys.mAllCacheKeys) == false)
                    {
                        StringBuilder strBuilder = new StringBuilder("#");
                        bool blnRemoveOverFlow = m_CacheBase.Count >= mintMaxCacheNum;
                        int intIndexCahce = 0;
                        int intRemoveCount = m_CacheBase.Count - mintMaxCacheNum + 1;
                        foreach (string strTemp in m_CacheBase.GetData(CacheKeys.mAllCacheKeys).ToString().Split('#'))
                        {
                            if (Yorkg.Base.Common.TypeHelper.IsEmpty(strTemp) == false && IsExist(strTemp))
                            {
                                intIndexCahce++;
                                if (intIndexCahce <= intRemoveCount)
                                    Remove(strTemp);
                                else
                                    strBuilder.Append(strTemp + "#");
                            }
                        }
                        m_CacheBase.Add(CacheKeys.mAllCacheKeys, strBuilder.ToString());
                    }
                }
            }
        }
        /// <summary>
        /// 根据正则删除 
        /// </summary>
        /// <param name="oEnumSubmitResult">EnumSubmitResult 如果Success 才会执行删除</param>
        /// <param name="strDelReg">缓存的正则</param>
        /// <returns></returns>
        public EnumSubmitResult RemoveKeysByEnumSubmitResult(EnumSubmitResult oEnumSubmitResult, string strDelReg)
        {
            if (oEnumSubmitResult == EnumSubmitResult.Success)
            {
                RemoveByRegexp(strDelReg);
            }
            return oEnumSubmitResult;
        }
        #endregion

    }
}
